from django import template
from django.utils.safestring import mark_safe, SafeData
from django.template.defaultfilters import stringfilter
from django.template import resolve_variable
from datetime import datetime
from simplepages.models import Page, SiteSection

register = template.Library()

def main_menu(request):
    main_menu = SiteSection.objects.menu_items()
    for menu in main_menu:
        if menu.url != '/':
            if request.path.find(menu.url) >= 0:
                menu.current = True
            else:
                menu.current = False
    return {'main_menu': main_menu }    
register.inclusion_tag('pages/main_menu.html')(main_menu)

def autolinebreaks(value, autoescape=None):
    """
    Checks if the content is html or plain text if plain text 
    replaces line breaks with appropriate HTML; a single
    newline becomes an HTML line break (``<br />``) and a new line
    followed by a blank line becomes a paragraph break (``</p>``).
    """
    import re
    html_match = re.compile('<br>|<br />|<p>|<table>', re.IGNORECASE)
    if not html_match.search(value):
        from django.utils.html import linebreaks
        autoescape = autoescape and not isinstance(value, SafeData)
        return mark_safe(linebreaks(value, autoescape))
    else:
        return value
autolinebreaks.is_safe = True
autolinebreaks.needs_autoescape = True
autolinebreaks = stringfilter(autolinebreaks)
register.filter(autolinebreaks)